using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Text.RegularExpressions;
using DevExpress.Accessibility;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Drawing;
using DevExpress.XtraEditors.Registrator;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraEditors.ViewInfo;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Registrator;
using DevExpress.XtraGrid.Views.BandedGrid;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid.Views.Grid;

namespace QuanLyThuNgan
{
    public class CustomDevExpressGrid : GridControl
    {
        private GridView _gridView;

        protected override void RegisterAvailableViewsCore(InfoCollection collection)
        {
            base.RegisterAvailableViewsCore(collection);
            collection.Add(new CustomDevExpressGridViewInfoRegistrator());
        }

        protected override BaseView CreateDefaultView()
        {
            return CreateView("CustomDevExpressGridView");
        }

        private void InitializeComponent()
        {
            _gridView = new GridView();
            ((ISupportInitialize) (_gridView)).BeginInit();
            ((ISupportInitialize) (this)).BeginInit();
            SuspendLayout();
            // 
            // _gridView
            // 
            _gridView.GridControl = this;
            _gridView.Name = "_gridView";
            // 
            // CustomDevExpressGrid
            // 
            MainView = _gridView;
            ViewCollection.AddRange(new BaseView[]
                                        {
                                            _gridView
                                        });
            ((ISupportInitialize) (_gridView)).EndInit();
            ((ISupportInitialize) (this)).EndInit();
            ResumeLayout(false);
        }
    }

    public class CustomDevExpressGridView : GridView
    {
        public CustomDevExpressGridView()
            : this(null)
        {
        }

        public CustomDevExpressGridView(GridControl gc)
            : base(gc)
        {
            CustomDrawCell += CustomDevExpressGridViewCustomDrawCell;
        }

        private void CustomDevExpressGridViewCustomDrawCell(object sender, RowCellCustomDrawEventArgs e)
        {
            if (e.DisplayText.Contains("PLUG"))
            {
                ;
            }
            e.Appearance.FillRectangle(e.Cache, e.Bounds);
            e.Appearance.DrawString(e.Cache, e.DisplayText, e.Bounds);
            e.Handled = true;
        }

        protected override string ViewName
        {
            get { return "CustomDevExpressGridView"; }
        }

        protected override string OnCreateLookupDisplayFilter(string text, string displayMember)
        {
            return BuildCustomContainsFilterFromValue(text, displayMember);
        }

        private string BuildCustomContainsFilterFromValue(string stringToFormFilterWith, string columnName)
        {
            if (string.IsNullOrEmpty(stringToFormFilterWith)) return string.Empty;
            var wildCarded = ToContainsFriendlySearch(stringToFormFilterWith);

            // only one word
            if (!wildCarded.Contains("%"))
                return "[" + columnName + "] Like '%" + wildCarded + "%'";

            var splitUpWords = wildCarded.Split('%');
            var sb = new StringBuilder();
            foreach (var word in splitUpWords)
            {
                sb.Append(" [" + columnName + "] Like '%" + word + "%' AND");
            }

            return sb.ToString().TrimEnd(new char[3] {'A', 'N', 'D'});
        }

        public string ToContainsFriendlySearch(string parameter)
        {
            if (string.IsNullOrEmpty(parameter)) return null;
            var wildCardedString = Regex.Replace(parameter.Trim(), @"[\s\p{P}]+", "%");
            return wildCardedString.Trim('%');
        }
    }

    public class CustomDevExpressGridViewInfoRegistrator : GridInfoRegistrator
    {
        public override string ViewName
        {
            get { return "CustomDevExpressGridView"; }
        }

        public override BaseView CreateView(GridControl grid)
        {
            return new CustomDevExpressGridView(grid);
        }
    }

    [UserRepositoryItem("RegisterCustomEdit")]
    public class CustomDevExpressGridLookUpEdit : RepositoryItemGridLookUpEdit
    {
        //The static constructor which calls the registration method 
        static CustomDevExpressGridLookUpEdit()
        {
            RegisterCustomEdit();
        }

        //The unique name for the custom editor 
        public const string CustomEditName = "DerivedLookUpEdit";

        //Return the unique name 
        public override string EditorTypeName
        {
            get { return CustomEditName; }
        }

        //Register the editor 
        public static void RegisterCustomEdit()
        {
            //Icon representing the editor within a container editor's Designer 
            Image img = null;
            EditorRegistrationInfo.Default.Editors.Add(new EditorClassInfo(CustomEditName, typeof(DerivedLookUpEdit),
                                                                           typeof(CustomDevExpressGridLookUpEdit),
                                                                           typeof(GridLookUpEditBaseViewInfo),
                                                                           new ButtonEditPainter(), true, img,
                                                                           typeof(PopupEditAccessible)));
        }

        protected override GridControl CreateGrid()
        {
            return new CustomDevExpressGrid();
        }

        protected override GridView CreateViewInstance()
        {
            switch (ViewType)
            {
                case GridLookUpViewType.BandedView:
                    return new BandedGridView();
                case GridLookUpViewType.AdvBandedView:
                    return new AdvBandedGridView();
            }
            return new CustomDevExpressGridView();
        }
    }

    public class DerivedLookUpEdit : GridLookUpEdit
    {
        //The static constructor which calls the registration method 
        static DerivedLookUpEdit()
        {
            CustomDevExpressGridLookUpEdit.RegisterCustomEdit();
        }

        //Initialize the new instance 
        public DerivedLookUpEdit()
        {
            //... 
        }

        //Return the unique name 
        public override string EditorTypeName
        {
            get { return CustomDevExpressGridLookUpEdit.CustomEditName; }
        }

        //Override the Properties property 
        //Simply type-cast the object to the custom repository item type 
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        public new CustomDevExpressGridLookUpEdit Properties
        {
            get { return (CustomDevExpressGridLookUpEdit)base.Properties; }
        }
    }
}